package com.duojuhe.coremodule.monitor.service.impl;

import com.duojuhe.cache.LoginUserTokenCache;
import com.duojuhe.common.bean.UserTokenInfoVo;
import com.duojuhe.common.component.checkauth.DataAuthCheck;
import com.duojuhe.common.result.ErrorCodes;
import com.duojuhe.common.result.PageResult;
import com.duojuhe.common.result.ServiceResult;
import com.duojuhe.common.utils.listutil.PageModel;
import com.duojuhe.common.utils.page.PageHelperUtil;
import com.duojuhe.coremodule.BaseService;
import com.duojuhe.coremodule.monitor.pojo.dto.online.user.MonitorUserOnlineIdReq;
import com.duojuhe.coremodule.monitor.pojo.dto.online.user.QueryMonitorUserOnlinePageReq;
import com.duojuhe.coremodule.monitor.pojo.dto.online.user.QueryMonitorUserOnlinePageRes;
import com.duojuhe.coremodule.monitor.service.MonitorUserOnlineService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MonitorUserOnlineServiceImpl  extends BaseService implements MonitorUserOnlineService {
    @Resource
    private LoginUserTokenCache loginUserTokenCache;
    @Resource
    private DataAuthCheck dataAuthCheck;

    /**
     * 分页查询 根据条件查询在线用户list
     */
    @Override
    public ServiceResult<PageResult<List<QueryMonitorUserOnlinePageRes>>> queryMonitorUserOnlinePageResList(QueryMonitorUserOnlinePageReq req) {
        try {
            //返回值
            List<QueryMonitorUserOnlinePageRes>  list = buildQueryMonitorUserOnlinePageResList(req);
            if(req.getRows()==0){
                return PageHelperUtil.returnServiceResult(req,list);
            }
            //每页显示条数
            PageModel pm = new PageModel(list, req.getRows());
            //页数
            int page = req.getPage();
            //显示第几页
            List sublist = pm.getObjects(page);
            pm.setList(sublist);
            return PageHelperUtil.returnServiceResult(req,pm.getList());
        } catch (Exception e) {
            log.info("根据条件查询在线用户集合异常",e);
            return ServiceResult.fail(ErrorCodes.FAIL);
        }
    }


    /**
     * 根据在线id强制踢出
     */
    @Override
    public ServiceResult forceKickOutOnlineUserByOnlineId(MonitorUserOnlineIdReq req) {
        try {
            String onlineId = req.getOnlineId();
            //当前登录人
            UserTokenInfoVo userTokenInfoVo = getCurrentLoginUserInfoDTO();
            if (userTokenInfoVo.getToken().equals(onlineId)){
                return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
            }
            loginUserTokenCache.forceKickOutOnlineUserByToken(onlineId);
            return ServiceResult.ok(onlineId);
        } catch (Exception e) {
            log.info("根据在线ID强制踢出异常",e);
            return ServiceResult.fail(ErrorCodes.FAIL);
        }
    }


    /**
     * 构建在线用户返回对象集合
     * @param req
     * @return
     */
    private List<QueryMonitorUserOnlinePageRes> buildQueryMonitorUserOnlinePageResList(QueryMonitorUserOnlinePageReq req){
        //所有登录会话
        List<UserTokenInfoVo> tokenInfoVoList = loginUserTokenCache.getAllAdminUserInfoListCache();
        if (StringUtils.isNotBlank(req.getLoginName())){
            tokenInfoVoList = tokenInfoVoList.stream().filter(e->e.getLoginName().contains(req.getLoginName())).collect(Collectors.toList());
        }
        if (StringUtils.isNotBlank(req.getRealName())){
            tokenInfoVoList = tokenInfoVoList.stream().filter(e->e.getRealName().contains(req.getRealName())).collect(Collectors.toList());
        }
        List<QueryMonitorUserOnlinePageRes>  list = new ArrayList<>();
        //当前登录人
        UserTokenInfoVo userTokenInfoVo = getCurrentLoginUserInfoDTO();
        //获取用户id集合
        List<String> allowOperationUserIdList = dataAuthCheck.getAllowOperationUserIdList(null,userTokenInfoVo);
        if (allowOperationUserIdList!=null){
            for (UserTokenInfoVo userToken:tokenInfoVoList){
                //如果token用户是当前登录用户或者已被踢出的用户，不在显示在列表中
                if (userToken.getKickOut() || userToken.getToken().equals(userTokenInfoVo.getToken())
                        || !allowOperationUserIdList.contains(userToken.getUserId())){
                    continue;
                }
                list.add(new QueryMonitorUserOnlinePageRes(userToken.getToken(),userToken));
            }
        }else {
            for (UserTokenInfoVo userToken:tokenInfoVoList){
                //如果token用户是当前登录用户或者已被踢出的用户，不在显示在列表中
                if (userToken.getKickOut() || userToken.getToken().equals(userTokenInfoVo.getToken())){
                    continue;
                }
                list.add(new QueryMonitorUserOnlinePageRes(userToken.getToken(),userToken));
            }
        }
        return list;
    }
}
